include $(CURDIR)/makelib/bmakelib.mk
include $(CURDIR)/makelib/config.mk

# Establish the prefix for !!logged-tagged targets.
ROOT = microlibs-

TEST_INCLUDES = $(wildcard ./libs/*/*.h)
TEST_SOURCES = $(patsubst %.h, %_test.c, $(TEST_INCLUDES))
TEST_EXECUTABLES = $(patsubst %.c, %, $(TEST_SOURCES))
TEST_DFILES = $(patsubst %, %.d, $(TEST_EXECUTABLES))

.PHONY: build build-impl clean_logs display_grind_results grind grind-impl run clean targets

# Default target lists available targets and their intent.
targets:
	@echo "User-facing targets:"
	@echo "  build     - Build all test executables, reporting build timing."
	@echo "  clean     - Remove generated files."
	@echo "  grind     - Build all test executables, reporting build timing."
	@echo "              Run tests under Valgrind."
	@echo "              Log output to 'microlibs-run-<timestamp>.logged'."
	@echo "  targets   - Display this help message.  (default)"
	@echo "As well as each individual test executable:"
	@echo "$(foreach exe, $(TEST_EXECUTABLES), $(shell printf '\t%s\\n' $(exe)))"

# Build tests.
build: build-impl!timed
# Because !timed cannot be applied to multi-value variables, build is broken into a separate target.
build-impl: $(TEST_EXECUTABLES)

# Build and valgrind tests.
grind: build-impl!timed clean_logs grind-impl!!logged display_grind_results
# Because !!logged cannot be applied to multi-value variables, run is broken into a separate target.
grind-impl: $(TEST_EXECUTABLES)
	@FAILED=0;                                \
	for test in $(TEST_EXECUTABLES); do       \
		echo "Grinding $$test ...";       \
		$(VALGRIND) $$test;               \
		if [ $$? -eq 0 ]; then            \
			echo "... $$test PASSED"; \
		else                              \
			echo "... $$test FAILED"; \
			FAILED=$$((FAILED + 1));  \
		fi;                               \
	done;

clean_logs:
	@rm -vf *.logged

display_grind_results:
	@grep --color=always -e "^... .*_test " *.logged

-include $(CURDIR)/makelib/marker.mk

clean:
	@rm -vf $(TEST_EXECUTABLES)
	@rm -vf $(TEST_DFILES)
	@rm -vf *.logged

-include $(TEST_DFILES)
